//
//  AppDelegate.m
//  diaoyuren
//
//  Created by 钓鱼人 on 15/12/18.
//  Copyright © 2015年 game. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarController.h"
#import "LoginController.h"
#import "ChangyanSDK.h"
#import "PersonageController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
#import "WeiboSDK.h"
#import "GuideViewController.h"

//BMKMapManager * _mapManager;
@implementation AppDelegate

-(void)setIsLogin:(NSString *)isLogin{

    _isLogin = isLogin;
    if ([self.isLogin isEqualToString:@"YES"]) {
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        self.UserName =[ud valueForKey:@"userName"];
        self.UserPass = [ud valueForKey:@"userPass"];
        
//        //账户密码，加密字典
//        self.UserDic = @{
//                         @"username":[Manager doEncryptStr:self.UserName withKey:@"diaoyurbbs"],
//                         @"password":[Manager doEncryptStr:self.UserPass withKey:@"diaoyurbbs"],
//                         };
        [[Manager sharedManager]RequestWhithURL:[NSString stringWithFormat:SetLoginTime,(3600*24)*10] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        }];//设置登录时间  账号在后台的登录的持续时间

        [self GetUserInform];
    }
}

#pragma mark--获取个人信息
-(void)GetUserInform{
    
    [[Manager sharedManager]ResponseWhithURL:@"http://api.diaoyur.cn/app/index.php?version=4&module=member" AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            self.UserDataGet = @"YES";
            
            self.userModel = [[UserDataModel alloc]initWithDictionary:responseObject[@"data"][@"member"] error:nil];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginNotifi" object:nil userInfo:@{@"sss":self.userModel}];//发送通知
            
            [self LoginChangYanWhithUserId:self.userModel.uid AndHeard:self.userModel.avatar AndName:self.userModel.username];

            NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
          
            [ud setObject:responseObject[@"data"][@"member"] forKey:@"userInform"];
            [ud setObject:responseObject[@"data"][@"formhash"] forKey:@"formhash"];
            
            UINavigationController * nav = self.myTabBar.viewControllers[3];
            PersonageController * personCtl = nav.viewControllers.firstObject ;
            [personCtl GetUserData];
    
        }else{
            self.isLogin = @"NO";
        }
    }];
}


#pragma mark--发表评论前登录畅言
-(void)LoginChangYanWhithUserId:(NSString *)userId AndHeard:(NSString *)headurl AndName:(NSString *)name{
    
    [ChangyanSDK loginSSO:userId
                 userName:name
               profileUrl:nil
                   imgUrl:headurl
            completeBlock:^(CYStatusCode statusCode, NSString *responseStr) {
                
                if ([responseStr isEqualToString:@"Login Success!"]) {
                    self.ChangYanIsLogin = YES;
                    
                }else{
                    self.ChangYanIsLogin = NO;
                }
            }];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

//    判断程序是否是第一次启动办法是 2 个key: @”everLaunched”判断用户以前是否登录,
//    @”firstLaunch” 用来开发者在程序的其他部分判断.
//    在第一次启动的时候 key @”everLaunched” 不会被赋址的, 并且设置为YES. @”firstLaunch” 被设置为 YES.
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
    
//在程序的其他部分用以下代码判断:
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
//
        GuideViewController *view = [GuideViewController new];
        self.window.rootViewController = view;
       [self.window makeKeyAndVisible];
//
    }else {
        TabBarController *tab = [[TabBarController alloc]init];
        self.myTabBar = tab;
        self.window.rootViewController = tab;
        [self.window makeKeyAndVisible];
//        设置一个图片;
        UIImageView *niceView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, screen_width, SCREEN_HEIGHT)];
        niceView.image = [UIImage imageNamed:@"钓鱼人750x1334"];
        
        //添加到场景
        [self.window addSubview:niceView];
        
        //放到最顶层;
        [self.window bringSubviewToFront:niceView];
        [UIView transitionWithView:niceView duration:0.7 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            niceView.alpha = 0.0;
            niceView.frame = CGRectMake(-60, -85, SCREEN_WIDTH+120, SCREEN_HEIGHT+170);
        } completion:nil];

    }
            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
        _mapManager = [[BMKMapManager alloc]init];
        // 5Lu6Z6CxGQ8FKLQTElkZFUgtbbBvpADv  fuyang--rQSN5cOA3LDoP16Tk74AIAbpVNxGaOi9
        //老板---USRxRBV8GewsGBvHZQ50KcWXuGIceoZX
        [_mapManager start:@"5Lu6Z6CxGQ8FKLQTElkZFUgtbbBvpADv"  generalDelegate:self];
    
        /*畅言SDK*/
        [ChangyanSDK registerApp:@"cyr7BCq8w"
                          appKey:@"d27c5b58a7e8632eb82aa7e6555098bc"
                     redirectUrl:@"http://www.diaoyur.com"
            anonymousAccessToken:@"0xfjqSBj7QkJzKYCvPVlyYV0VYmJzOgPiUWA5-TAZDY"];
    
//        您的ShareSDK的AppKey e2a4da9051ac
        [ShareSDK registerApp:@"e2a4da9051ac" activePlatforms:@[@(SSDKPlatformTypeSinaWeibo),@(SSDKPlatformSubTypeQZone),@(SSDKPlatformSubTypeWechatSession),@(SSDKPlatformSubTypeWechatTimeline),@(SSDKPlatformSubTypeQQFriend)] onImport:^(SSDKPlatformType platformType) {
            
            switch (platformType)
            {
                    
                case SSDKPlatformTypeSinaWeibo:
                    [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                    break;
                    
                case SSDKPlatformTypeWechat:
                    [ShareSDKConnector connectWeChat:[WXApi class]];
                    break;
                case SSDKPlatformTypeQQ:
                    [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                    break;
                    
                default:
                    break;
            }
        } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
            switch (platformType)
            {
                case SSDKPlatformTypeSinaWeibo:
                    //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                    [appInfo SSDKSetupSinaWeiboByAppKey:@"1128429965"
                                              appSecret:@"b5520068507f0838c5cdd5b1d21ad441"
                                            redirectUri:nil
                                               authType:SSDKAuthTypeBoth];
                    break;
                case SSDKPlatformTypeWechat:
                    [appInfo SSDKSetupWeChatByAppId:@"wxa834f3eb613553bf"
                                          appSecret:@"4bcb3caf1c08fc0216db4c04a68a2277"];
                    break;
                case SSDKPlatformTypeQQ:
                    [appInfo SSDKSetupQQByAppId:@"310439456"
                                         appKey:@"KEYc4L8aneBLhaqtplw"
                                       authType:SSDKAuthTypeBoth];
                    break;
                    break;
                default:
                    break;
            }
        }];
        return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end